package de.unibielefeld.msp.zusatzstoffe;

import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import de.unibi.techfak.msp.eatThis.bean.FoodBean;
import de.unibielefeld.msp.zusatzstoffe.utility.Constants;
import de.unibielefeld.msp.zusatzstoffe.utility.ServiceConsumer;
import flexjson.JSONSerializer;

/**
 * @author Moritz Jülkenbeck <mjulken@techfak.uni-bielefled.de>
 * 
 */
public class NewFoodActivity extends Activity {

    /** Key for the extra that can be passed to this activity. */
    public static final String EAN_KEY = "ean";
    
    /** TAG for logging. */
    public static final String TAG = "NewFoodActivity";

    /** View elements. */
    private EditText eanInput;
    private EditText nameInput;
    private EditText ingredientsInput;
    private EditText groupInput;
    private Button sendBtn;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.newfood);

        eanInput = (EditText) findViewById(R.id.newfood_ean_input);
        nameInput = (EditText) findViewById(R.id.newfood_name_input);        
        ingredientsInput = (EditText) findViewById(R.id.newfood_ingredients_input);       
        groupInput = (EditText) findViewById(R.id.newfood_group_input);
        sendBtn = (Button) findViewById(R.id.newfood_btn_send);
    }

    @Override
    protected void onResume() {
        super.onResume();

        Bundle extras = getIntent().getExtras();

        /* check if the activity is called with a give EAN. If so use the EAN
         * and disable the corresponding field. */
        if (extras == null) {
            eanInput.setEnabled(true);
            return;
        }

        String ean = extras.getString(EAN_KEY);

        eanInput.setText(ean);
        eanInput.setEnabled(false);

    }

    /**
     * Is called when the send button is used.
     * 
     * @param view
     */
    public void onClickSend(View view) {
        sendBtn.setEnabled(false);
        String sendText = (String) sendBtn.getText();
        sendBtn.setText("Please Wait...");
        
        String ean = eanInput.getText().toString();
        String name = nameInput.getText().toString();
        String group = groupInput.getText().toString();
        String ingredients = ingredientsInput.getText().toString();
        
        FoodBean fb = new FoodBean();
        fb.setName(name);
        fb.setGroup(group);
        fb.setIngredients(ingredients);
        fb.setEan(ean);
        
        if (fb.getName() == null || fb.getGroup() == null) {
            CharSequence text = "Fehler! Bitte alle Felder ausfüllen!";
            Toast.makeText(getApplicationContext(), text, Toast.LENGTH_LONG).show();
        } else {
            new SendFoodBean().execute(new JSONSerializer().serialize(fb));
        }
        sendBtn.setText(sendText);
        sendBtn.setEnabled(true);
        
    }

    public class SendFoodBean extends AsyncTask<String, Void, Integer> {

        private final ProgressDialog dialog = new ProgressDialog(
                NewFoodActivity.this);

        // can use UI thread here
        @Override
        protected void onPreExecute() {
            this.dialog.setMessage("Inserting Food ...");
            this.dialog.show();
        }

        @Override
        protected Integer doInBackground(String... params) {
            HttpPost httppost = new HttpPost(Constants.CONNECTION_PREFIX);
            HttpResponse response = null;

            try {

                httppost.setEntity(new StringEntity(params[0]));
                
                Log.d(TAG, httppost.toString());

                response = ServiceConsumer.execute(httppost);
                
                if (response == null) {
                    return -1;
                }
            } catch (Exception e) {
                
                Log.e(TAG, "Fehler bei HTTPPost!\n" + e.toString());

                return -1;
            }
            return 0;
        }

        @Override
        protected void onPostExecute(final Integer result) {
            if (this.dialog.isShowing()) {
                this.dialog.dismiss();
            }
            switch (result) {
                case -1:
                    CharSequence text = "Fehler beim Erstellen!";
                    Toast toast = Toast.makeText(getApplicationContext(), text,
                            Toast.LENGTH_SHORT);
                    toast.show();
                    break;
                case 0:
                    CharSequence text2 = "Erstellen erfolgreich!";
                    Toast toast2 = Toast.makeText(getApplicationContext(),
                            text2, Toast.LENGTH_SHORT);
                    toast2.show();
                    break;

                default:
                    break;
            }
        }

    }

}
